global class IntegrationUtill
{
    public static boolean isRunTest = false;
    @future(callout= true)
    public static void doCalloutEduMxService(Set<String> setOppIdsStage,Boolean isRunningTest) {
        //Add code to perform callout 
        Set<String> setOppIds = new Set<String>();
        Map<string,string> mapIdStage= new Map<String,String>();
        
        for(String s : setOppIdsStage)
        {
            string ids = s.substring(s.indexOf('-')+1 );
            string stgnme = s.subString(0,s.indexOf('-'));
            setOppIds.add(s.substring(s.indexOf('-')+1 ));
            mapIdStage.put(ids,stgnme);
            system.debug('############### ' + stgnme+ ' #####------------------');
        }
         system.debug('------------ ' + setOppIds + ' ---------------------');       
        List<Opportunity> lst_Opportunity = [ Select Id, Account.Id, Account.PersonEmail,Account.Student_ID__c,Account.Last_Last_Name__pc,Account.FirstName ,Account.Birth_Date__c, Account.LastName , Account.CURP__c, Account.Phone, Account.Father_s_First_Name__c, Account.Gender__pc,Student_ID__c,Quoted_Tuition_discount__c,Quoted_Registration_discount__c,Account.Exterior_Number__c ,Account.Interior_Number__c, Account.Personal_Email__pc,Account.Other_Street__c, Account.PersonBirthdate,
        Catalog__r.ID,Catalog__r.System_ID__c,Catalog__r.Catalog_ID__c,Feeder_School__r.School_Code__c, Account.recordtypeId, recordtypeId from Opportunity where id IN : setOppIds] ;
        List<Integration_Log__c> lst_IntegrationLog = new List<Integration_Log__c>();
        List<Opportunity> lst_OpportunityToUpdate = new List<Opportunity>();
        List<Opportunity> lst_OpportunityToUpdateWithFailure = new List<Opportunity>();
        List<Account> lst_AccountToUpdate = new List<Account>();
        boolean docall;
        String oppRecTypId = '';
        String accRecTypeID = '';
        
        Map<String,String> accountRecordTypes = new Map<String,String>{}; 
        Map<String,String> opportunityRecordTypes = new Map<String,String>{};        
        
        List<RecordType> r = [Select r.SobjectType, r.Name, r.developername, r.IsActive, r.Id From RecordType r where ((Sobjecttype='Opportunity') AND (isActive =true) )];
        for(RecordType rt: r)
            opportunityRecordTypes.put(rt.developername,rt.Id);
            oppRecTypId = opportunityRecordTypes.get('ULA_Tradional_Locking_Layout');
        
        List<RecordType> r2 = [Select r2.SobjectType, r2.Name, r2.developerName, r2.IsActive, r2.Id From RecordType r2 where ((Sobjecttype='Account') AND (isActive =true) )];
        for(RecordType rtt: r2)
            accountRecordTypes.put(rtt.developerName,rtt.Id);
            accRecTypeID = accountRecordTypes.get('ULA_Traditional_Locking_Student_Account');
        
        for(Opportunity opp : lst_Opportunity)
        {     
             ulaEdu_Request_Element req_OBJ = new ulaEdu_Request_Element(); 
             //docall = false;
             if(opp.Account.Student_ID__c != null)
             {
                 req_OBJ.IdentifierNumber = opp.Account.Student_ID__c;                 
             }
             else
             {
                 req_OBJ.IdentifierNumber = '';
              //   docall = true;
             }   
             if(opp.Account.LastName != null)
             {
                 req_OBJ.LastName = opp.Account.LastName;
             }
             else
             {
                 req_OBJ.LastName = '';
             }
             if(opp.Account.FirstName != null)
             {
                 req_OBJ.FirstName = opp.Account.FirstName;
             }    
             else
             {
                 req_OBJ.FirstName = '';
             }            
             if(opp.Account.Last_Last_Name__pc != null)
             {
                 req_OBJ.LastLastName = opp.Account.Last_Last_Name__pc;
             }
             else
             {
                 req_OBJ.LastLastName = '';
             }
             if(opp.Account.Phone != null)
             {
                 req_OBJ.PhoneNumber = opp.Account.Phone;
             }
             else
             {
                 req_OBJ.PhoneNumber = '1231231234';
             }
             if(opp.Catalog__r.System_ID__c != null)
             {
                req_OBJ.PersonSystem = Integer.valueOf(opp.Catalog__r.System_ID__c);
             }
             else
             {
                req_OBJ.PersonSystem = 0;
             }
             req_OBJ.Country = 'US';
             req_OBJ.State = 0;
             req_OBJ.Province = 0;
             req_OBJ.Colony = 0;
             req_OBJ.Street = '1';
             req_OBJ.InternalNumberOfHouse = '';
             req_OBJ.ExternalNumberOfHouse = '';
             if(opp.Account.CURP__c != null)
             {
                req_OBJ.NationalId = opp.Account.CURP__c;
             }
             else
             {
                req_OBJ.NationalId = '';
             }
             if (opp.Feeder_School__r.School_Code__c != null)
             {
                 req_OBJ.FeederSchool = Integer.valueOf(opp.Feeder_School__r.School_Code__c);
             }
             else
             {
                 req_OBJ.FeederSchool = 1;
             } 
             if(opp.Account.Birth_Date__c != null)
             {
                String bday = String.ValueOf(opp.Account.Birth_Date__c.Day());
                if(bday.length()<2)
                {
                    bday = '0'+bday ;
                }
                String bmonth = String.ValueOf(opp.Account.Birth_Date__c.Month());
                if(bmonth.length()<2)
                {
                    bmonth = '0'+bmonth ;
                }
                String byear = String.ValueOf(opp.Account.Birth_Date__c.Year());
                
                req_OBJ.DateOfBirth = bday +bmonth +byear ;
             }
             else
             {
                req_OBJ.DateOfBirth = '';
             }
             if(opp.Account.PersonEmail != null)
             {
                req_OBJ.Email = opp.Account.PersonEmail;
             }
             else
             {
                req_OBJ.Email = '';
             }
             if (opp.Catalog__r.Catalog_ID__c != null)
             {
             req_OBJ.School = integer.valueof(opp.Catalog__r.Catalog_ID__c) ;
             }
             else
             {
                req_OBJ.School = 0;
             }
             if(opp.Account.Gender__pc == 'Male')
             {
                req_OBJ.Gender = '1';
             }
             else
             {
                req_OBJ.Gender = '0';
             }
             if(opp.Quoted_Tuition_discount__c != null)
             {
                
                req_OBJ.DiscountOnInscription = opp.Quoted_Tuition_discount__c.intValue();
             }
             else
             {
               req_OBJ.DiscountOnInscription = 0;
             }
             if(opp.Quoted_Registration_discount__c != null)
             {
                req_OBJ.DiscountOnScholarship = opp.Quoted_Registration_discount__c.intValue();
             }
             else
             {
               req_OBJ.DiscountOnInscription = 0;
             }
             System.debug('----- '+ req_OBJ);
             String ServiceResponse;
             String exceprtionstring;
             try
             {
                 //if(docall)
                 ServiceResponse = doCallULXMethod(req_OBJ,isRunningTest);  
             }
             catch(Exception ex)
             {
                exceprtionstring = ex.getmessage();
             }
             finally
             {           
                 Boolean isSuccess= false;
                 Id recId;
                 String callDate ;
                 String studentId ;
                 if(ServiceResponse  != null)
                 {
                     if(ServiceResponse.startsWith('1'))
                     {
                         isSuccess = true;
                         try
                         {
                         studentId = ServiceResponse.substring(ServiceResponse.indexof('|')+1,ServiceResponse.lastIndexOf('|'));
                         callDate =  ServiceResponse.substring(ServiceResponse.lastIndexOf('|')+1, ServiceResponse.length());            
                         lst_IntegrationLog.add(new Integration_Log__c(Opportunity__c=opp.id,Status__c='Sucess',Request__c = String.valueOf(req_OBJ),Response__c = ServiceResponse));
                         }Catch(Exception ext)
                         {
                             isSuccess  = false;
                             lst_IntegrationLog.add(new Integration_Log__c(Opportunity__c=opp.id,Status__c='Error',Request__c = String.valueOf(req_OBJ),Response__c = ServiceResponse,Detail__c = ext.GetMessage()));                       
                         }
                     }            
                 }
                 else
                 {
                     isSuccess = false;
                 }
                
                 // Updating Records
                 if(isSuccess)
                 {
                     String codeNumber = StudentNumberLogic.getCheckDigitString(studentId);
                     if(opp.Account.Student_Id__c == null)
                     {
                         System.debug('++++++++++ISSUCCESS++++++++++ ' + ServiceResponse);
                        
                         lst_OpportunityToUpdate.add(new Opportunity(id= opp.id,Digit_Verification__c=codeNumber , Student_Id__c = studentId, recordTypeId = oppRecTypId));
                         lst_AccountToUpdate.add(new Account(Id=opp.Account.id,Digit_Verification__c=codeNumber ,Student_ID__c = studentId, recordtypeId = accRecTypeID));
                     }
                     else
                     {
                           //opp.Account.Student_Id__c = 'opp.Account.Student_Id__c';
                           lst_OpportunityToUpdate.add(new Opportunity(id= opp.id, Digit_Verification__c=codeNumber ,Student_Id__c = studentId, recordTypeId = oppRecTypId));  
                           lst_AccountToUpdate.add(new Account(Id=opp.Account.id,Digit_Verification__c=codeNumber ,Student_ID__c = studentId, recordtypeId = accRecTypeID));
                     }                
                 }
                 else
                 {
                     System.debug('++++++++++ISFailure++++++++++ ' + exceprtionstring);
                     lst_OpportunityToUpdateWithFailure.add(new Opportunity(id= opp.id, StageName = mapIdStage.get(opp.id)));
                     lst_IntegrationLog.add(new Integration_Log__c(Opportunity__c=opp.id,Status__c='Failed',Request__c = String.valueOf(req_OBJ),Response__c = ServiceResponse, Detail__c=' Serer is not Responding . Returning ZERO'+exceprtionstring));
                 }
                 System.debug(studentId+'--++++++ '+ isSuccess  + callDate );   
                 System.debug('++++++++++RR++++++++++ ' + ServiceResponse);
             }
             if(lst_OpportunityToUpdate.size()>0)
             {
                 update lst_OpportunityToUpdate;
                
                 System.debug('+++++++++update hui list++++++++ '+ oppRecTypId + ' 7777777777777 ' + accRecTypeID );
                 update lst_AccountToUpdate;
             }
             if(lst_OpportunityToUpdateWithFailure.size()>0)
             {
                update lst_OpportunityToUpdateWithFailure ;
             }
             if(lst_IntegrationLog.size()>0)
             {
                 insert lst_IntegrationLog;
             }
         }
     }
     public class ulaEdu_Request_Element {
         String IdentifierNumber{get;set;}
         String LastName{get;set;}
         String FirstName{get;set;}
         String LastLastName{get;set;}
         Integer PersonSystem{get;set;}
         String Country{get;set;}
         Integer State{get;set;}
         Integer Province{get;set;}
         Integer Colony{get;set;}
         String Street{get;set;}
         String InternalNumberOfHouse{get;set;}
         String ExternalNumberOfHouse{get;set;}
         String PhoneNumber{get;set;}
         String NationalId{get;set;}
         Integer FeederSchool{get;set;}
         String DateOfBirth{get;set;}
         String Email{get;set;}
         Integer School{get;set;}
         String Gender{get;set;}
         Integer DiscountOnInscription{get;set;}
         Integer DiscountOnScholarship{get;set;}
         }
    public Static String doCallULXMethod(ulaEdu_Request_Element ulx_obj,boolean isRunningtst)
    {        
        ulaEduMxUlaServices.ULAServicesSoap  Soap_OBJ = new ulaEduMxUlaServices.ULAServicesSoap();
        return Soap_OBJ.registerDataApplicant(ulx_obj.IdentifierNumber, ulx_obj.LastName, ulx_obj.FirstName, ulx_obj.LastLastName, ulx_obj.PersonSystem, ulx_obj.Country, ulx_obj.State, ulx_obj.Province, ulx_obj.Colony, ulx_obj.Street, ulx_obj.InternalNumberOfHouse, ulx_obj.ExternalNumberOfHouse, ulx_obj.PhoneNumber, ulx_obj.NationalId, ulx_obj.FeederSchool, ulx_obj.DateOfBirth, ulx_obj.Email, ulx_obj.School, ulx_obj.Gender, ulx_obj.DiscountOnInscription, ulx_obj.DiscountOnScholarship,isRunningtst);
            
    }
}